/**
 * Doubly linked list
 */
#include "list.h"

#define WRITE_ONCE_LIST(var, val) (*((volatile plist_head_t *)(&(var))) = (val))

void INIT_LIST_HEAD(struct list_head *list)
{
	WRITE_ONCE_LIST(list->next, list);
	list->prev = list;
}

/*
* Insert a newl entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static void __list_add(struct list_head *newl,
	struct list_head *prev,
	struct list_head *next)
{
	next->prev = newl;
	newl->next = next;
	newl->prev = prev;
	WRITE_ONCE_LIST(prev->next, newl);
}

/**
* list_add_tail - add a newl entry
* @newl: newl entry to be added
* @head: list head to add it before
*
* Insert a newl entry before the specified head.
* This is useful for implementing queues.
*/
void list_add_tail(struct list_head *newl, struct list_head *head)
{
	__list_add(newl, head->prev, head);
}

/*
* Delete a list entry by making the prev/next entries
* point to each other.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static void __list_del(struct list_head * prev, struct list_head * next)
{
	next->prev = prev;
	WRITE_ONCE_LIST(prev->next, next);
}

/**
* list_del - deletes entry from list.
* @entry: the element to delete from the list.
* Note: list_empty() on entry does not return true after this, the entry is
* in an undefined state.
*/
static void __list_del_entry(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
}

/**
* list_del_init - deletes entry from list and reinitialize it.
* @entry: the element to delete from the list.
*/
void list_del_init(struct list_head *entry)
{
	__list_del_entry(entry);
	INIT_LIST_HEAD(entry);
}

/**
* list_empty_careful - tests whether a list is empty and not being modified
* @head: the list to test
*
* Description:
* tests whether a list is empty _and_ checks that no other CPU might be
* in the process of modifying either member (next or prev)
*
* NOTE: using list_empty_careful() without synchronization
* can only be safe if the only activity that can happen
* to the list entry is list_del_init(). Eg. it cannot be used
* if another CPU could re-list_add() it.
*/
int list_empty_careful(const struct list_head *head)
{
	struct list_head *next = head->next;
	return (next == head) && (next == head->prev);
}
